<html>
	<head>
		<title>1b</title>
	</head>
	<body>
		<form method="POST">
			Input your SQL query:
			<br />
			<textarea name="query" rows="5" cols="50"></textarea>
			<p></p>
			<input type="submit">
		</form>
		<?php
		error_reporting(0);
		if (!empty($_POST)) {
			// connect to the database
			$link = mysql_connect("localhost", "cs143", "");
			if (!$link)
				die("<span style='color:red'>Error</span>: " . mysql_error());
			// select database
			$sdb = mysql_select_db("CS143");
			if (!$sdb)
				die("<span style='color:red'>Error</span>: " . mysql_error());

			// query
			$query = mysql_query($_POST['query']);
			if (!$query)
				die("<span style='color:red'>Error</span>: " . mysql_error());

			// show table header
			echo '<table border="1"><tr>';
			$total_fields = mysql_num_fields($query);
			for ($i = 0; $i < $total_fields; ++$i) {
				$meta = mysql_fetch_field($query, $i);
				echo '<th>' . $meta->name . '</th>';
			}
			echo '</tr>';

			// show content of the table
			while ($row = mysql_fetch_array($query)) {
				echo '<tr>';
				for ($i = 0; $i < $total_fields; ++$i) {
					echo '<td>' . ($row[$i] == '' ? 'N/A' : $row[$i]). '</td>';
				}
				
				echo '</tr>';
			}
			echo '</table>';
			mysql_free_result($query);
			mysql_close();

		}
		?>
	</body>
</html>
